class Cate {
  tableHead = {
    id: "ID",
    pid: "父级ID",
    title: "标题",
    sort: "排序",
    status: "状态",
    created_time: "创建时间",
    updated_time: "修改时间",
    operate: "操作",
  };

  constructor(isIndex = false) {
    if (isIndex) {
      this.setTableHead();
      this.getCateList();
      let keyWord = document.getElementById("keyWord");
      let keyValue = document.getElementById("keyValue");

      document.getElementById("sreach").onclick = () =>
        this.getCateList(keyWord, keyValue.value);
    }
  }

  /**
   * 请求列表
   */
  getCateList(keyWord = [], keyValue = "") {
    let data = {};
    if (keyWord.value) {
      data[keyWord.value] = keyValue;
    }
    Request.post("/admin/cate/getList", data).then((res) => {
      this.handleView(res.data);
    });
  }

  setTableHead() {
    let tr = document.createElement("tr");
    Reflect.ownKeys(this.tableHead).forEach((item, index) => {
      let th = document.createElement("th");
      th.innerHTML = this.tableHead[item];
      th.id = item;
      tr.append(th);
    });
    document.getElementById("head").append(tr);
  }

  /**
   * 渲染列表
   *
   * @param {*} data
   * @returns
   */
  handleView(data = {}) {
    //初始化
    document.getElementById("cate").innerHTML = "";

    if (!data || Object.keys(data).length === 0) return;

    const tableHeadKeys = Reflect.ownKeys(this.tableHead);

    data.forEach((item) => {
      let tr = document.createElement("tr");

      tableHeadKeys.forEach((key) => {
        let td = document.createElement("td");

        if (key === "operate") {
          td.innerHTML = `
            <button class="edit-btn" data-id="${item.id}">编辑</button>
            <button class="delete-btn" data-id="${item.id}">删除</button>
          `;
        } else if (key === "status") {
          td.innerHTML = item[key] == 1 ? "启用" : "禁用";
        } else {
          switch (typeof item[key]) {
            case "number":
              td.innerHTML = item[key] || 0;
              break;
            case "string":
              td.innerHTML = item[key] || "--";
              break;
            default:
              td.innerHTML = item[key] || "";
              break;
          }
        }

        tr.append(td);
      });
      document.getElementById("cate").append(tr);
    });
  }

  addCate() {
    let pid = document.getElementById("pid").value;
    let title = document.getElementById("title").value;
    let sort = document.getElementById("sort").value;
    let data = { pid, title, sort };
    Request.post("/admin/cate/create", data).then((res) => {
      console.log(res);
    });
  }
}

let pathArr = location.href.split("/");
let lastPath = pathArr.pop();

switch (lastPath) {
  case "cate.html": //首页
    new Cate(true);
    break;
  default:
    break;
}
